import axios from "axios";
import Qs from "qs";

//请求拦截
axios.interceptors.request.use((request) => {
    // 设置基础 URL
    // request.baseURL = "http://10.10.233.100:8888/p4java"
    // request.baseURL = "http://localhost:8888/p4java"
    // request.baseURL = "http://192.168.1.229:8888/p4java"
    request.baseURL = "http://admin.free.svipss.top/p4java"

    /*if (request.url.indexOf('file') != -1) {
        request.baseURL = "http://localhost:2002"
    }
    if (request.url.indexOf('chart') != -1) {
        request.baseURL = "http://localhost:10020"
    }*/
    if (request.url == "https://jsonplaceholder.typicode.com/posts/") {
        request.baseURL = "https://jsonplaceholder.typicode.com/posts/"
    }
    // 设置请求头
    request.headers = {
        "content-type": "application/json;charset=utf-8",
    }
    if (request.url == "/file/file/file" || request.url == "/file/file/files") {
        request.headers = {
            "content-type": "multipart/form-data",
        }
    }
    let isLogin = window.localStorage.getItem("isLogin");
    if (isLogin) {
        request.headers.Authorization = window.localStorage.getItem("token");
    }
    /*if(request.method=='POST'){
        request.data = Qs.stringify(request.data, {arrayFormat: 'indices', allowDots: true});
    }*/
    return request;
}, (error) => {
    //请求出错处理逻辑
    return Promise.reject(error)
});

//响应拦截
axios.interceptors.response.use((response) => {
    //将 data 数据返回,项目中 this.axios的 then 获取的数据就是 data ,我们需要的真实数据了
    let data = response.data;
    return data;
}, (error) => {
    let httpCode = error.response.status;
    let message;
    if (httpCode === 200) {
        //响应出错处理逻辑
        let code = error.response.data.code;
        let msg = error.response.data.msg;
        switch (code) {
            case 10000:
                message = msg;
                break;
            case 50000:
                message = '未知异常! 请联系管理员';
                break;
            case 50002:
                message = msg;
                break;
            case 50003:
                message = msg;
                break;
            case 50004:
                message = msg;
                break;
        }
    } else {
        switch (httpCode) {
            case 504:
                message = "网关超时,请重试或联系管理员";
                break;
            default:
                message = '未知异常! 请联系管理员';
                break;
        }
    }
    window.vm.$Message.error({
        background: true,
        content: message,
        duration: 5,
        closable: true
    });
    return Promise.reject(error)
});